<?php
/**
 * @package   Options_Framework
 * 
 */

class Options_Framework_Admin {

	/**
     * Page hook for the options screen
     *
     * @type string
     */
    protected $options_screen = null;

    /**
     * Save notice info
     * @type string
     */
    protected $notice = null;


    /**
     * Hook in the scripts and styles
     *
     */
    public function init() {
        
		// Gets options to load
    	$options = & Options_Framework::_optionsframework_options();
       
		// Checks if options are available
    	if ( $options ) {

			// Add the options page and menu item.
			add_action( 'admin_menu', array( $this, 'add_custom_options_page' ) );

			// Add the required scripts and styles
			add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_styles' ) );
			add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );

			// Settings need to be registered after admin_init
			add_action( 'admin_init', array( $this, 'settings_init' ) );

			// Adds options menu to the admin bar
			add_action( 'wp_before_admin_bar_render', array( $this, 'optionsframework_admin_bar' ) );

		}

    }

	/**
     * Registers the settings
     * 
     */
    function settings_init() {

    	// Load Options Framework Settings
        $optionsframework_settings = get_option( 'apollo_optionsframework' );

		// Registers the settings fields and callback
		register_setting( 'optionsframework', $optionsframework_settings['id'],  array ( $this, 'validate_options' ) );

		// Displays notice after options save
		add_action( 'optionsframework_after_validate', array( $this, 'save_options_notice' ) );

    }

	/*
	 * Define menu options (still limited to appearance section)
	 *
	 * Examples usage:
	 *
	 * add_filter( 'optionsframework_menu', function( $menu ) {
	 *     $menu['page_title'] = 'The Options';
	 *	   $menu['menu_title'] = 'The Options';
	 *     return $menu;
	 * });
	 *
	 *
	 */
	static function menu_settings() {

		$menu = array(
			'page_title' => __( 'Theme Options', 'apollo' ),
			'menu_title' => __( 'Theme Options', 'apollo' ),
			'capability' => 'edit_theme_options',
			'menu_slug' => 'options-framework'
		);

		return apply_filters( 'optionsframework_menu', $menu );
	}

	/**
     * Add a subpage called "Theme Options" to the appearance menu.
     */
	function add_custom_options_page() {
        
		$menu = $this->menu_settings();
		$this->options_screen = add_theme_page( $menu['page_title'], $menu['menu_title'], $menu['capability'], $menu['menu_slug'], array( $this, 'options_page' ) );

	}

	/**
     * Loads the required stylesheets
     *
     */
	function enqueue_admin_styles( $hook ) {

		if ( $this->options_screen != $hook )
	        return;
		wp_enqueue_style( 'optionsframework', OPTIONS_FRAMEWORK_DIRECTORY . 'css/optionsframework.css', array(), Options_Framework::VERSION );
		wp_enqueue_style( 'wp-color-picker' );
	}

	/**
     * Loads the required javascript
     *
     */
	function enqueue_admin_scripts( $hook ) {

		if ( $this->options_screen != $hook )
	        return;

		// Enqueue custom option panel JS
		wp_enqueue_script( 'theme-options-function', OPTIONS_FRAMEWORK_DIRECTORY . 'js/theme-options-function.js', array( 'jquery','wp-color-picker' ), Options_Framework::VERSION );

		// Inline scripts from options-interface.php
		add_action( 'admin_head', array( $this, 'of_admin_head' ) );
	}

	function of_admin_head() {
		// Hook to add custom scripts
		do_action( 'optionsframework_custom_scripts' );
	}

	/**
     * Builds out the options panel.
     *
	 * If we were using the Settings API as it was intended we would use
	 * do_settings_sections here.  But as we don't want the settings wrapped in a table,
	 * we'll call our own custom optionsframework_fields.  See options-interface.php
	 * for specifics on how each individual field is generated.
	 *
	 * Nonces are provided using the settings_fields()
	 *
     */
	 function options_page() { ?>

		<div id="optionsframework-wrap" class="wrap">

		<?php $menu = $this->menu_settings(); ?>
		<h2><?php echo esc_html( $menu['page_title'] ); ?></h2>

	    <h2 class="nav-tab-wrapper">
	        <?php echo Options_Framework_Interface::optionsframework_tabs(); ?>
	    </h2>

	    <?php settings_errors( 'options-framework' ); ?>

	    <div id="optionsframework-metabox" class="metabox-holder">
		    <div id="optionsframework" class="postbox">
				<form action="options.php" method="post">
				<?php settings_fields( 'optionsframework' ); ?>
				<?php Options_Framework_Interface::optionsframework_fields(); /* Settings */ ?>
				<div id="optionsframework-submit">
					<input type="submit" class="button-primary" name="update" value="<?php esc_attr_e( 'Save Options', 'apollo' ); ?>" />
					<input type="submit" class="reset-button button-secondary" name="reset" value="<?php esc_attr_e( 'Restore Defaults', 'apollo' ); ?>" onclick="return confirm( '<?php print esc_js( __( 'Click OK to reset. Any theme settings will be lost!', 'apollo' ) ); ?>' );" />
					<div class="clear"></div>
				</div>
				</form>
			</div> <!-- / #container -->
		</div>
		
		</div> <!-- / .wrap -->

	<?php
	}

	/**
	 * Validate Options.
	 *
	 * This runs after the submit/reset button has been clicked and
	 * validates the inputs.
	 *
	 * @uses $_POST['reset'] to restore default options
	 */
	function validate_options( $input ) {
        
		/*
		 * Restore Defaults.
		 *
		 * In the event that the user clicked the "Restore Defaults"
		 * button, the options defined in the theme's options.php
		 * file will be added to the option for the active theme.
		 */

		if ( isset( $_POST['reset'] ) ) {
           
			add_settings_error( 'options-framework', 'restore_defaults', __( 'Default options restored.', 'apollo' ), 'updated fade' );
           
			return $this->get_default_values();
		}

		/*
		 * Update Settings
		 *
		 * This used to check for $_POST['update'], but has been updated
		 * to be compatible with the theme customizer introduced in WordPress 3.4
		 */

		$clean = array();
		$options = & Options_Framework::_optionsframework_options();
		foreach ( $options as $option ) {

			if ( ! isset( $option['id'] ) ) {
				continue;
			}

			if ( ! isset( $option['type'] ) ) {
				continue;
			}

			$id = preg_replace( '/[^a-zA-Z0-9._\-]/', '', strtolower( $option['id'] ) );

			// Set checkbox to false if it wasn't sent in the $_POST
			if ( 'checkbox' == $option['type'] && ! isset( $input[$id] ) ) {
				$input[$id] = false;
			}

			// Set each item in the multicheck to false if it wasn't sent in the $_POST
			if ( 'multicheck' == $option['type'] && ! isset( $input[$id] ) ) {
				foreach ( $option['options'] as $key => $value ) {
					$input[$id][$key] = false;
				}
			}

			// For a value to be submitted to database it must pass through a sanitization filter
			if ( has_filter( 'of_sanitize_' . $option['type'] ) ) {
				$clean[$id] = apply_filters( 'of_sanitize_' . $option['type'], $input[$id], $option );
			}
		}
       
        // Update override css
        $this->update_override_css( $input ); 
        
        // Update primary color css
        $this->update_primary_color_css( $input ); 
        
        // Load override css
        $clean['apollo_override_css'] = @file_get_contents(get_override_css_abs_path() );
		
        // Hook to run after validation
		do_action( 'optionsframework_after_validate', $clean );
        $clean['apollo_override_css'] = '';
		return $clean;
	}
    
    /**
     * Update override css
     * @param string $css CSS content
     * @return void
     */ 
    function update_override_css( $input ) {
        
        $file = get_override_css_abs_path();
        if (is_writable( $file ) ) {
            @chmod($file, 0777);
        }
        
        @file_put_contents( $file, $input['apollo_override_css'] );  
        $sites = get_current_site();
        if ( !is_writable($file) ) {
            $this->notice = __('Can not write override css file. Please set write permission for ', 'apollo'). 'wp-content/themes/apollo/sites/'.$sites->domain;
            return false;
        }
        
    }
    
    public static function update_primary_color_css( $input ) {
        
        // Update primary color 
        $color = $input['apollo_primary_color'];
        
        $hover_active_step = check_is_bright_color( $color ) ? -15 : 50 ;
        
        $css_content = ''
            . '.main-menu, .blog-itm .b-time, '
            . '.r-search .r-ttl i.fa { '
            . 'background: '.$color. ' ;'
            . '}'
            . '.r-blk .r-ttl { color: '.$color. ' ; }'
            . '.main-menu .mn-menu .nav > li > a { border-top: 3px solid '.$color. ' ; }'
            . '.b-btn a.btn-b, .btn.btn-l { border: 1px solid '.$color. ' ; }'
            . '.top-head .top-blk a:hover { color: '.$color.' }'
            . '.main-menu .mn-menu .nav > li.cur > a { background: '.adjust_brightness( $color, $hover_active_step ).'; } '
            
            . '.form-event .s-rw .lst-lik a:hover, .btn.btn-l:hover, .newsletter-frm .btn.btn-l:hover, '
            . '.calendar-ipt .btn.btn-l:hover, .sub-blk .btn.btn-l:hover, btn.btn-l:hover, .b-btn a.btn-b:hover {background: '.$color. '  ;border: 1px solid '.$color. ' ;}'
            . '@media (max-width: 767px) {'
            . '.main-menu.tablet-show.show {background: '.$color.'}'
            . 'a.mb-menu.active { background: '. $color .'; border-color: '.$color.' }'
            . ''
            . '}';

        $file = get_primary_color_css_abs_path();
      
        @file_put_contents( $file, $css_content );   
        $sites = get_current_site();
        if ( !is_writable( $file ) ) {
            $this->notice = __('Can not write Primary color css file. Please set write permission for ', 'apollo'). 'wp-content/themes/apollo/sites/'.$sites->domain;
            return false;
        }
        
    }
    
    /**
	 * Display message when options have been saved
	 */

	function save_options_notice() {
      
		add_settings_error( 'options-framework', 'save_options', 
            $this->notice ? $this->notice : __('Options saved', 'apollo') , 'updated fade' );
        
        // Update option override css to empty
        $optionsframework_settings = get_option( 'apollo_optionsframework' );
        $optionsframework_settings['apollo_override_css'] = '';
        update_option('apollo_optionsframework', $optionsframework_settings);
        
	}

	/**
	 * Get the default values for all the theme options
	 *
	 * Get an array of all default values as set in
	 * options.php. The 'id','std' and 'type' keys need
	 * to be defined in the configuration array. In the
	 * event that these keys are not present the option
	 * will not be included in this function's output.
	 *
	 * @return array Re-keyed options configuration array.
	 *
	 */

	function get_default_values() {
		$output = array();
		$config = & Options_Framework::_optionsframework_options();
		foreach ( (array) $config as $option ) {
			if ( ! isset( $option['id'] ) ) {
				continue;
			}
			if ( ! isset( $option['std'] ) ) {
				continue;
			}
			if ( ! isset( $option['type'] ) ) {
				continue;
			}
			if ( has_filter( 'of_sanitize_' . $option['type'] ) ) {
				$output[$option['id']] = apply_filters( 'of_sanitize_' . $option['type'], $option['std'], $option );
			}
		}
        // Update override css
        $this->update_override_css( $input ); 
        
        $this->update_primary_color_css( $output );
        
		return $output;
	}

	/**
	 * Add options menu item to admin bar
	 */

	function optionsframework_admin_bar() {

		$menu = $this->menu_settings();
		global $wp_admin_bar;

		$wp_admin_bar->add_menu( array(
			'parent' => 'appearance',
			'id' => 'of_theme_options',
			'title' => __( 'Theme Options', 'apollo' ),
			'href' => admin_url( 'themes.php?page=' . $menu['menu_slug'] )
		) );
	}

}
